package com.xsf.pay.common.exception;


import com.xsf.pay.common.constants.ExceptionConstants;
import com.xsf.pay.common.domain.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author 呆毛一哥
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST) //设置状态码为 400
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultData<Object> paramExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                return ResultData.fail(fieldError.getDefaultMessage());
            }
        }
        return ResultData.fail("请求参数错误");
    }
    /**
     * 参数异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessParamCheckingException.class)
    @ResponseBody
    public ResultData<Object> businessParamCheckingException(BusinessParamCheckingException e) {
        log.error("BusinessParamCheckingException ERROR:",e);
        return new ResultData<>(e.getCode(),e.getMessage());
    }

    /**
     * 运行异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessRunTimeException.class)
    @ResponseBody
    public ResultData<Object> businessRunTimeException(BusinessRunTimeException e) {
        log.error("BusinessRunTimeException ERROR:",e);
        return new ResultData<>(e.getCode(),e.getMsg());
    }

    /**
     * 运行异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ResultData<Object> illegalArgumentExceptionException(IllegalArgumentException e) {
        log.error("BusinessRunTimeException ERROR:", e);
        return new ResultData<>(ExceptionConstants.SERVICE_SYSTEM_ERROR_CODE, e.getMessage());
    }

    /**
     * 全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultData<Object> handleException(Exception e) {
        log.error("Exception ERROR:",e);
        return new ResultData<>(ExceptionConstants.SERVICE_SYSTEM_ERROR_CODE,ExceptionConstants.SERVICE_SYSTEM_ERROR_MSG);
    }

}
